package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 *
 * @Title: 微信小程序页面调用API*
 */

public class apiWXMiniPCall implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXMiniPCall.class);
    private static String defaultUrl = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        try {
            //解析Json
            JSONObject inJson = JSONObject.fromObject(inData);
            defaultUrl = KHDBConfig.getParam(eliteBean, "WXPPIC");

            String type = inJson.getString("type");
            if (type == "onLoad") {
                String expand = inJson.getJSONObject("data").getString("expand");
                log.info("[调用请求信息expand]:" + expand);

                if (expand == "3") {
                    result = doDocumentURL(jt, inJson);
                } else {
                    result = doPAShortURL(jt, inJson);

                }

            } else {
                result.put("code", -1);
                result.put("msg", type);
                result.put("data", []);
            }
            log.info("调用处理结果：" + result.toString());

        } catch (Exception e) {
            log.error("数据处理错误Exception-", e);
            result.put("code", 1006);
            result.put("msg", "数据处理错误");
        }

        return result.toString();
    }

    public static JSONObject doPAShortURL(JdbcTemplate jt, JSONObject inJson) {

        JSONObject result = new JSONObject();
        try {
            //解析Json
            String recid = inJson.getString("recid");
            String expand = inJson.getString("data");
            String openid = inJson.getString("openid");

            List<Map<String, Object>> selectCus = null;
            if (!KHUtil.isNull(recid) && recid != "undefined") {
                String selectSQL = '''Select Replace(Pic_Url_Arr, 'https://dev-cc.kuangheng.com', 'https://jzzy.futures.pingan.com') As Pic_Url_Arr From Wx_Shortenurl_Map Where Recid = ? Limit 1''';
                selectCus = jt.queryForList(selectSQL, recid);
                log.debug("通过RecID获取海报信息..." + selectCus.toString());

            } else {

                String selectSQL = '''Select Replace(R1.Pic_Url_Arr, 'https://dev-cc.kuangheng.com', 'https://jzzy.futures.pingan.com') As Pic_Url_Arr
                                              From Wx_Shortenurl_Map R1
                                              Left Join Wx_Shortenurl_Visit R2
                                                On R1.Recid = R2.Map_Recid
                                             Where R2.Openid = ?
                                             Order By Visit_Time Desc Limit 1''';
                selectCus = jt.queryForList(selectSQL, openid);
                log.debug("通过OpenID获取海报信息..." + selectCus.toString());

            }

            String[] imageArr = null;
            if (selectCus.size() > 0) {
                imageArr = selectCus.get(0).get("Pic_Url_Arr").toString().split(";");

                result.put("code", 1);
                result.put("msg", expand);
                result.put("data", imageArr);

            } else {
                result.put("code", 2);
                result.put("msg", expand);
                result.put("data", []);

                // 如果系统参数配置的图片不为空则默认返回配置
                if (!KHUtil.isNull(defaultUrl)) {
                    JSONArray imgArrj = new JSONArray();
                    imgArrj.add(defaultUrl);
                    result.put("data", imgArrj);

                }
            }
            jt.update("Insert Into Wx_Shortenurl_Visit (Recid, Map_Recid, Openid, Visit_Time, Visit_Url) Values (Uuid(), ?, ?, Now(),?)", recid, openid, imageArr.toString());

            log.info("调用处理结果：" + result.toString());

        } catch (Exception e) {
            log.error("数据处理错误Exception-", e);
            result.put("code", 1006);
            result.put("msg", "数据处理错误");
        }
        return result;
    }

    public static JSONObject doDocumentURL(JdbcTemplate jt, JSONObject inJson) {
        JSONObject result = new JSONObject();

        try {
            //解析Json
            String recid = inJson.getString("recid");
            String expand = inJson.getString("data");
            String openid = inJson.getString("openid");

            // 查询是否存在
            String selectSQL = "";
            List<Map<String, Object>> selectCus = null;

            if (!KHUtil.isNull(recid) && recid != "undefined") {
                selectSQL = '''Select DocumentOut_Guid, OpenID, Replace(Stringfield1, 'https://dev-cc.kuangheng.com', 'https://jzzy.futures.pingan.com') As Stringfield1 From Documentout Where Stringfield1 is not null and Stringfield1 != '' and Documentout_Guid = ? Limit 1''';
                selectCus = jt.queryForList(selectSQL, recid);
                log.debug("通过RecID获取海报信息..." + selectCus.toString());

            } else {
                selectSQL = '''Select DocumentOut_Guid, OpenID, Replace(Stringfield1, 'https://dev-cc.kuangheng.com', 'https://jzzy.futures.pingan.com') As Stringfield1 From Documentout Where Stringfield1 is not null and Stringfield1 != '' and OpenID = ? Order By CREATEDDATE Desc Limit 1''';
                selectCus = jt.queryForList(selectSQL, openid);
                log.debug("通过OpenID获取海报信息..." + selectCus.toString())

            }
            if (selectCus.size() > 0) {
                String Documentout_Guid = selectCus.get(0).get("DocumentOut_Guid").toString();
                String[] imageArr = selectCus.get(0).get("Stringfield1").toString().split(";");

                jt.update("Update Documentout Set Passflag = 1, Stringfield2 = Now(), OpenID = ? Where Documentout_Guid = ?", openid, Documentout_Guid);

                jt.update("Insert Into Wx_Shortenurl_Visit (Recid, Map_Recid, Openid, Visit_Time, Visit_Url) Values (Uuid(), ?, ?, Now(),?)", recid, openid, imageArr.toString());

                result.put("code", 1);
                result.put("msg", expand);
                result.put("data", imageArr);
            } else {
                result.put("code", 2);
                result.put("msg", expand);
                result.put("data", []);

                // 如果系统参数配置的图片不为空则默认返回配置
                if (!KHUtil.isNull(defaultUrl)) {
                    JSONArray imgArrj = new JSONArray();
                    imgArrj.add(defaultUrl);
                    result.put("data", imgArrj);

                }
            }

            log.info("调用处理结果：" + result.toString());

        } catch (Exception e) {
            log.error("", e);
            result.put("code", 1006);
            result.put("msg", "数据处理错误");
        }
        return result;
    }

}
